package com.xyauto.theme.vm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.TextUtils
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import com.arialyy.annotations.Download
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.inf.IEntity
import com.arialyy.aria.core.task.DownloadTask
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ZipUtils
import com.xyauto.theme.App
import com.xyauto.theme.Constant
import com.xyauto.theme.R
import com.xyauto.theme.base.SingleLiveEvent
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.utils.getFileNameByUrl
import kotlinx.coroutines.delay
import java.io.File

class DetailViewModel : BaseThemeModel() {


    private var dataBean: IThemeBean? = null

    val typeObserver by lazy { SingleLiveEvent<Int>() }
    val detailObserver by lazy { SingleLiveEvent<IThemeBean>() }
    val progressObserver by lazy { MutableLiveData<TaskStatus>() }

    fun loadDataBean(bean: IThemeBean?) = bean?.let {
        dataBean = it
        detailObserver.postValue(it)

        LogUtils.i("loadDataBean: name=${it.getName()}+apkPath=${it.getApkPath()}+previewImage=${it.getPreviewImage()}")

        var type = 0;
        // spot:1 判断是否为选中的
        if (it.isSelected()) {
            type = R.string.detail_text_in_use
        }
        // spot:2 判断theme是否存在的
        if (type == 0 && it.isExists()) {
            type = R.string.detail_text_apply
        }
        // spot:3 判断是否存在下载过程
        if (type == 0 && !TextUtils.isEmpty(it.getUrlPath())) {
            val entity = getTaskPair(dataBean)?.entity
            val status = entity?.state
            LogUtils.i(status, entity?.id)
            typeObserver.value = when (status) {
                IEntity.STATE_COMPLETE -> if (it.isExists()) R.string.detail_text_apply else R.string.detail_text_download

                IEntity.STATE_FAIL -> R.string.detail_text_resume
                IEntity.STATE_STOP -> R.string.detail_text_resume

                IEntity.STATE_RUNNING -> R.string.detail_text_downloading
                IEntity.STATE_PRE -> R.string.detail_text_downloading
                IEntity.STATE_POST_PRE -> R.string.detail_text_downloading

                else -> R.string.detail_text_download
            }
        } else {
            typeObserver.postValue(type)
        }
    }

    fun reloadDataBean() {
        loadDataBean(dataBean)
    }


    fun onApply(context: Context) {
        launchNo({
            dataBean?.let { item ->
                selectTheme(context, item)
            } ?: false
        }, {
            typeObserver.postValue(R.string.detail_text_in_use)
            if (!it) {
                clearObserver.postValue(true)
            }
        })

    }

    fun onDownload() {
        val create = getTaskPair(dataBean)?.create()
        LogUtils.i("onDownload:$create")
    }

    fun resetDownloadTask() {
        val create = getTaskPair(dataBean)?.create()
        LogUtils.i("resetDownloadTask:$create")
    }


    private fun getTaskPair(bean: IThemeBean?) = bean?.getUrlPath()?.let { url ->
        val separator = File.separator
        val dirPath = "${separator}${Constant.getSavePath(bean.getVersion())}${separator}${bean.getName()}${separator}${getFileNameByUrl(url)}"
        Aria.download(this)
            .load(url)
            .setFilePath(dirPath)
            .ignoreCheckPermissions()
            .ignoreFilePathOccupy()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun registerBroadcast() {
        Aria.download(this).register()
        App.instance.registerReceiver(myBroadcastReceiver, IntentFilter(Constant.ZIP_COMPLETE_BROADCAST))
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun unregisterBroadcast() {
        Aria.download(this).unRegister()
        App.instance.unregisterReceiver(myBroadcastReceiver)
    }

    @Download.onPre
    @Download.onTaskComplete
    @Download.onTaskRunning
    @Download.onTaskStop
    @Download.onTaskFail
    fun onTaskRun(entity: DownloadTask?) {
        val url = dataBean?.getUrlPath() ?: return
        val downloadEntity = entity?.entity ?: return
        if (downloadEntity.key != url) return
        launchNo({
            when (downloadEntity.state) {
                IEntity.STATE_COMPLETE -> TaskStatus(Constant.download_ing, 100)
                IEntity.STATE_FAIL -> TaskStatus(Constant.download_pause, msg = "STATE_FAIL")
                IEntity.STATE_STOP -> TaskStatus(Constant.download_pause)
                else -> TaskStatus(Constant.download_ing, downloadEntity.percent)
            }
        }, {
            LogUtils.i(it)
            progressObserver.postValue(it)
        })
    }

    private val myBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.also {
                val mUrl = dataBean?.getUrlPath() ?: return
                val iUrl = it.getStringExtra("url") ?: return
                if (mUrl == iUrl) {
                    progressObserver.postValue(TaskStatus(Constant.download_complete))
                }
            }
        }
    }

    data class TaskStatus(
        var type: Int = 0,
        var progress: Int = 0,
        var msg: String = ""
    )
}